import random
import string
from datetime import timedelta

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
from cloudinary.models import CloudinaryField

class User(AbstractUser):
    """扩展用户模型"""
    email = models.EmailField(verbose_name='邮箱', unique=True, null=True, blank=True)
    phone = models.CharField(max_length=15, unique=True, null=True, blank=True)
    avatar = CloudinaryField(
        'avatar',
        folder='meetlocal/avatars',
        null=True,
        blank=True,
    )
    bio = models.TextField(max_length=500, blank=True, verbose_name='个性签名')
    interests = models.JSONField(default=list, blank=True, verbose_name='兴趣标签')
    # 添加用户状态字段
    ACCOUNT_STATUS = [
        ('active', '正常'),
        ('banned', '封禁'),
        ('deleted', '删除')
    ]
    account_status = models.CharField(
        max_length=10,
        choices=ACCOUNT_STATUS,
        default='active',
        verbose_name='账户状态'
    )

    # 封禁相关字段
    banned_until = models.DateTimeField(null=True, blank=True, verbose_name='封禁至')
    ban_reason = models.TextField(blank=True, verbose_name='封禁原因')
    privacy_level = models.CharField(
        max_length=20,
        choices=[
            ('public', '公开'),
            ('friends', '仅好友可见'),
            ('private', '私密')
        ],
        default='public'
    )
    points = models.IntegerField(default=0, verbose_name='积分')
    created_at = models.DateTimeField(auto_now_add=True)

    qq_openid = models.CharField(max_length=64, unique=True, null=True, blank=True, verbose_name='QQ OpenID')

    @property
    def is_banned(self):
        """检查用户是否被封禁"""
        if self.account_status == 'banned':
            if self.banned_until and timezone.now() < self.banned_until:
                return True
            elif self.banned_until and timezone.now() >= self.banned_until:
                # 封禁期满，自动恢复
                self.account_status = 'active'
                self.banned_until = None
                self.ban_reason = ''
                self.save()
                return False
            return True
        return False

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def get_avatar_url(self):
        """安全地获取用户头像URL"""
        try:
            # 如果头像存储在 User 模型中
            if hasattr(self, 'avatar') and self.avatar:
                return self.avatar.url
            # 或者如果头像存储在 UserProfile 中
            elif hasattr(self, 'userprofile') and self.userprofile.avatar:
                return self.userprofile.avatar.url
            else:
                return '/static/images/default-avatar.png'
        except Exception:
            return '/static/images/default-avatar.png'


class UserProfile(models.Model):
    """用户档案扩展"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    location = models.CharField(max_length=100, blank=True, verbose_name='所在地')
    birthday = models.DateField(null=True, blank=True)
    avatar = CloudinaryField('image', folder='meetlocal/avatars', null=True, blank=True)
    gender = models.CharField(
        max_length=10,
        choices=[('male', '男'), ('female', '女'), ('other', '其他')],
        blank=True
    )
    social_links = models.JSONField(default=dict, blank=True)

    class Meta:
        db_table = 'user_profiles'
        verbose_name = '用户档案'
        verbose_name_plural = verbose_name

    def get_gender_display(self):
        """获取性别显示值"""
        gender_map = {
            'male': '男',
            'female': '女',
            'other': '其他'
        }
        return gender_map.get(self.gender, '未设置')


class PasswordResetCode(models.Model):
    email = models.EmailField(verbose_name="邮箱")
    code = models.CharField(max_length=6, verbose_name="验证码")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    is_used = models.BooleanField(default=False, verbose_name="是否已使用")

    class Meta:
        db_table = 'user_passwordresetcode'
        verbose_name = "密码重置验证码"
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def is_expired(self):
        """检查验证码是否过期（5分钟内有效）"""
        return timezone.now() > self.created_at + timedelta(minutes=5)

    @classmethod
    def generate_code(cls, email):
        """生成验证码并保存"""
        # 生成6位随机数字验证码
        code = ''.join(random.choices(string.digits, k=6))
        # 保存验证码到数据库
        return cls.objects.create(email=email, code=code)


# 黑名单
class UserBlacklist(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='meet_user_blacklists'  # 修改为完全不同的名称
    )
    blocked_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='blocked_by_meet_users'  # 修改为完全不同的名称
    )
    created_at = models.DateTimeField(auto_now_add=True)
    reason = models.TextField(blank=True, null=True)

    class Meta:
        db_table = 'meet_user_blacklist'
        unique_together = ('user', 'blocked_user')
        verbose_name = 'Meet User Blacklist'
        verbose_name_plural = 'Meet User Blacklists'

    def __str__(self):
        return f"{self.user.username} blocked {self.blocked_user.username} in Meet"


# 新增关注模型 - 统一使用 UserFollow
class UserFollow(models.Model):
    """用户关注关系"""
    follower = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following_relationships',  # 我关注的人
        verbose_name='关注者'
    )
    following = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='follower_relationships',  # 关注我的人
        verbose_name='被关注者'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='关注时间')

    class Meta:
        db_table = 'user_follows'
        unique_together = ('follower', 'following')  # 防止重复关注
        verbose_name = '用户关注关系'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.follower.username} 关注 {self.following.username}"


class ChatGroup(models.Model):
    """聊天群组"""
    name = models.CharField(max_length=100, verbose_name='群组名称')
    description = models.TextField(blank=True, verbose_name='群组描述')
    avatar = CloudinaryField(
        folder='meetlocal/group_avatars',
        null=True,
        blank=True,
        verbose_name='群组头像'
    )
    creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_groups', verbose_name='创建者')
    members = models.ManyToManyField(User, through='GroupMembership', related_name='chat_groups', verbose_name='群成员')
    is_active = models.BooleanField(default=True, verbose_name='是否活跃')
    max_members = models.PositiveIntegerField(default=50, verbose_name='最大成员数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'chat_groups'
        verbose_name = '聊天群组'
        verbose_name_plural = '聊天群组'

    def __str__(self):
        return self.name

    def current_member_count(self):
        return self.members.count()

    def can_add_member(self):
        return self.current_member_count() < self.max_members


class GroupMembership(models.Model):
    """群组成员关系"""
    ROLE_CHOICES = [
        ('owner', '群主'),
        ('admin', '管理员'),
        ('member', '普通成员')
    ]

    group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, verbose_name='群组')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='member', verbose_name='角色')
    joined_at = models.DateTimeField(auto_now_add=True, verbose_name='加入时间')
    is_muted = models.BooleanField(default=False, verbose_name='是否禁言')

    class Meta:
        db_table = 'group_memberships'
        unique_together = ('group', 'user')
        verbose_name = '群组成员'
        verbose_name_plural = '群组成员'

    def __str__(self):
        return f"{self.user.username} - {self.group.name}"


class GroupMessage(models.Model):
    """群组消息"""
    group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='messages', verbose_name='群组')
    sender = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='发送者')
    content = models.TextField(verbose_name='消息内容')
    message_type = models.CharField(
        max_length=20,
        choices=[
            ('text', '文本'),
            ('image', '图片'),
            ('file', '文件'),
            ('system', '系统消息')
        ],
        default='text',
        verbose_name='消息类型'
    )
    is_read_by = models.ManyToManyField(User, through='MessageReadStatus', related_name='read_group_messages',
                                        blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')

    class Meta:
        db_table = 'group_messages'
        ordering = ['created_at']
        verbose_name = '群组消息'
        verbose_name_plural = '群组消息'

    def __str__(self):
        return f"{self.sender.username} 在 {self.group.name}: {self.content[:20]}"


class MessageReadStatus(models.Model):
    """消息阅读状态"""
    message = models.ForeignKey(GroupMessage, on_delete=models.CASCADE, verbose_name='消息')
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    read_at = models.DateTimeField(auto_now_add=True, verbose_name='阅读时间')

    class Meta:
        db_table = 'message_read_status'
        unique_together = ('message', 'user')
        verbose_name = '消息阅读状态'
        verbose_name_plural = '消息阅读状态'


class PrivateMessage(models.Model):
    """私信模型"""
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='sent_messages',
        verbose_name='发送者'
    )
    receiver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='received_messages',
        verbose_name='接收者'
    )
    content = models.TextField(verbose_name='消息内容')
    is_read = models.BooleanField(default=False, verbose_name='是否已读')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')

    class Meta:
        db_table = 'private_messages'
        ordering = ['-created_at']
        verbose_name = '私信'
        verbose_name_plural = '私信'


class ViolationReport(models.Model):
    """违规言论举报"""
    REPORT_TYPE_CHOICES = [
        ('private_message', '私信'),
        ('activity_discussion', '活动讨论'),
        ('activity_review', '活动评价'),
        ('discussion_comment', '讨论评论'),
    ]

    STATUS_CHOICES = [
        ('pending', '待审核'),
        ('approved', '违规确认'),
        ('rejected', '举报无效'),
        ('processed', '已处理'),
    ]

    reporter = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='submitted_reports',
        verbose_name='举报人'
    )
    reported_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='reported_violations',
        verbose_name='被举报用户'
    )
    report_type = models.CharField(max_length=20, choices=REPORT_TYPE_CHOICES, verbose_name='举报类型')
    source_id = models.CharField(max_length=100, verbose_name='来源ID')  # 存储私信ID、讨论ID等
    content = models.TextField(verbose_name='违规内容')
    reason = models.TextField(verbose_name='举报理由')
    screenshots = models.JSONField(default=list, blank=True, verbose_name='截图证据')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='处理状态')
    admin_notes = models.TextField(blank=True, verbose_name='管理员备注')
    action_taken = models.CharField(max_length=100, blank=True, verbose_name='处理措施')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='举报时间')
    processed_at = models.DateTimeField(null=True, blank=True, verbose_name='处理时间')
    processed_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='processed_violations',
        verbose_name='处理管理员'
    )

    class Meta:
        db_table = 'violation_reports'
        ordering = ['-created_at']
        verbose_name = '违规举报'
        verbose_name_plural = '违规举报'

    def __str__(self):
        return f"{self.reporter.username} 举报 {self.reported_user.username}"


class SystemMessage(models.Model):
    """系统消息"""
    MESSAGE_TYPE_CHOICES = [
        ('violation_warning', '违规警告'),
        ('violation_result', '举报处理结果'),
        ('account_banned', '账号封禁通知'),
        ('account_unbanned', '账号解封通知'),
    ]

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='system_messages',
        verbose_name='接收用户'
    )
    message_type = models.CharField(max_length=20, choices=MESSAGE_TYPE_CHOICES, verbose_name='消息类型')
    title = models.CharField(max_length=200, verbose_name='消息标题')
    content = models.TextField(verbose_name='消息内容')
    related_report = models.ForeignKey(
        ViolationReport,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name='相关举报'
    )
    is_read = models.BooleanField(default=False, verbose_name='是否已读')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')

    class Meta:
        db_table = 'system_messages'
        ordering = ['-created_at']
        verbose_name = '系统消息'
        verbose_name_plural = '系统消息'

    def __str__(self):
        return f"{self.user.username} - {self.title}"